package com.ghyf.mplay.view;

import java.util.ArrayList;
import java.util.ListIterator;

import com.ghyf.mplay.datatype.AlignMode;
import com.ghyf.mplay.datatype.BackParam;
import com.ghyf.mplay.datatype.FontParam;
import com.ghyf.mplay.datatype.RGBA;
import com.ghyf.mplay.datatype.ShowType;
import com.ghyf.mplay.util.LogUtil;
import com.ghyf.mplay.util.TypeFaceFactory;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 
 * 显示滚动文字的控件
 * @author cuiran
 * @version 1.0.0
 */
public class MScroll extends SurfaceView implements SurfaceHolder.Callback {
	private static final String TAG="MScroll";
	private int module_type; // 模块类型
	
	private int zOrder; // 模块的ZOrder
	
	private String file_version;	//文件版本
	
	private String module_name;	//控件名
	
	private int module_uid;//控件标识
	
	private int module_gid;//控件组标识
	

	private int refresh_time; // 滚动刷新的时间间隔
	private int scroll_pixel; // 滚动刷新的间距
	/***滚动上一文本和下一文本间距**/
	private int scroll_space=200; 
	
	
	
	protected SurfaceHolder holder=null;
	private Thread myThread;
	private int currentScrollX;// 当前滚动的位置

	public int getCurrentScrollX() {
		return currentScrollX;
	}

	public void setCurrentScrollX(int currentScrollX) {
		this.currentScrollX = currentScrollX;
	}
//	private String tempText="";
	private String currentText = "";
	private String nextText = "";
	private BackParam backgroud;
	private ArrayList<String> text_list;// 待显示的文本列表

	// <Align>5</Align>
	private AlignMode align;// 对齐方式

	// <Scroll_Type>0</Scroll_Type>
	private ShowType scroll_type;// 滚动文本的显示方式。

	
	private FontParam font;
	/**是否收到广播 默认false*/
	private volatile boolean isReceive	=false;
	/**是否添加***/
	private volatile boolean isAdd		=true;
	private ArrayList<String> temp_list=null;// 待显示的文本列表
	
	private Handler mHandler=new Handler();
	public MScroll(Context context) {
		super(context);
		holder = this.getHolder();
		holder.addCallback(this);
		holder.setFormat(PixelFormat.TRANSPARENT); // 顶层绘制SurfaceView设成透明
		this.setZOrderOnTop(true);
		
		
	}
	
	/* 自定义线程 */
	class MyRunnable implements Runnable {
		private Paint paint = null;
		private float textWidth;
		private ListIterator<String> listIterator = null;
		private int mWidth=0;
		private Canvas canvas = null;
		
		public void run() {
				//整个空间的宽度
			 mWidth=MScroll.this.getWidth();;
			while (!myThread.isInterrupted()) {
			
				try {
					
					synchronized (holder) {
					      draw();
					}
					Thread.sleep(getRefresh_time());
				} catch (InterruptedException e) {
					LogUtil.e(TAG, "ScrollSurfaceView：绘制失败...\r\n"
							+ e);
				} catch (Exception e) {
					LogUtil.e(TAG, "ScrollSurfaceView：run...\r\n"
							+ e);
				}
			}
		}

		private void draw(){
			//init paint
			if (paint == null) {
				initPaint();
				textWidth = paint.measureText(currentText);// 得到文本的长度。
			}
			currentScrollX -= scroll_pixel;// 滚动速度
//			LogUtil.i(TAG, "currentScrollX("+currentScrollX+"),scroll_pixel("+scroll_pixel+"),refresh_time("+refresh_time+")");
			canvas = holder.lockCanvas(new Rect(0, 0, MScroll.this
					.getWidth(), MScroll.this.getHeight())); // 获取画布
			// 退出时holder.lockCanvas（）方法可能返回空，避免报空指针异常
			if (canvas == null) return;
			// 清除画布方法一
			canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
			canvas.drawText(currentText, 0, currentText.length(),
						currentScrollX, paint.getTextSize(), paint);
			holder.unlockCanvasAndPost(canvas);// 解锁画布，提交画好的图像
			/**
			 * 1、currentScrollX+文本的宽度+200<=mWidth
			 */
				if((currentScrollX+textWidth+scroll_space)<=mWidth){
					currentText = currentText+"               "+nextText;
					textWidth = paint.measureText(currentText);// 得到文本的长度。
					if(textWidth>=mWidth*10){
						stopThread();
						startThread();
					}
					findNext();
				}
				
				if(isAdd){
					currentScrollX = MScroll.this.getWidth();
//					currentText=tempText;
					isAdd=false;
				}
			/**
			 * 2、滚动的文本结尾坐标=宽度的一半 显示 下一个文本
			 */
//			if (currentScrollX <= -textWidth) { // 滚完一屏文本后接着下一个文本。
//				currentScrollX = MScroll.this.getWidth();
//				currentText = nextText;
//				textWidth = paint.measureText(currentText);// 得到文本的长度。
//				findNext();
//				
//			}
			
		}
		/**
		 * 初始化paint
		 */
		public void initPaint() {
			paint = new Paint();
			if(isReceive&&null!=temp_list){
				listIterator = temp_list.listIterator();
			}else{
				listIterator = text_list.listIterator();
			}
			
			if (listIterator.hasNext()) {
				currentText = listIterator.next();
				findNext();
			}

			initFont(paint, font);

		}

		// 找到下一个文本。
		void findNext() {
			if (listIterator.hasNext()) {
				nextText = listIterator.next();
			} else { // 文本集合播完了就再播第一项。
				isAdd=true;
				while (listIterator.hasPrevious()) {
					listIterator.previous();
				}
				nextText = listIterator.next();
			}
		}

		/**
		 * 设置TextView的字体
		 * 
		 * @param paint
		 *            textview控件
		 * @param font
		 *            字体
		 */
		void initFont(Paint paint, FontParam font) {
			// paint.setTextAlign(Align.RIGHT);
			// 大小
			paint.setTextSize(font.getSize());
			// 字体
			Typeface typeface = TypeFaceFactory.createTypeface(font.getName());
			paint.setTypeface(typeface);
			// 颜色
			RGBA rgba = font.getFaceColor();
			int color = Color.argb(rgba.getAlpha(), rgba.getRed(),
					rgba.getGreen(), rgba.getBlue());
			paint.setColor(color);
			// TODO 其它字体参数的设置
		}

	}

	@Override
	/**
	 * 当控件创建时自动执行的方法
	 */
	public void surfaceCreated(SurfaceHolder holder) {
		// 启动自定义线程
		startThread();
	}
	
	Runnable runnable = new Runnable() { 
        @Override 
        public void run() { 
        	isReceive=false;
        	isAdd=true;
        	stopThread();
        	startThread();
        } 
    }; 

	public void startThread(){
		currentText="";
		LogUtil.i(TAG, "startThread");
		if(myThread!=null){
			stopThread();
		}
		myThread = new Thread(new MyRunnable());
		myThread.start();
		/**
		 * 如果有接收,计时10秒(暂定)，然后切回默认滚动播表 将isReceive 改为false
		 */
		if(isReceive){
			mHandler.postDelayed(runnable, 20000);
		}
		
	}
	public void stopThread(){
		LogUtil.i(TAG, "stopThread");
		// 终止自定义线程
		myThread.interrupt();
		myThread=null;
		System.gc();
	}
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	/**
	 * 当控件销毁时自动执行的方法
	 */
	public void surfaceDestroyed(SurfaceHolder holder) {
		stopThread();
	}

	public int getScroll_pixel() {
		return scroll_pixel;
	}

	public void setScroll_pixel(int scroll_pixel) {
		this.scroll_pixel = scroll_pixel;
	}

	public String getText() {
		return currentText;
	}

	public void setText(String text) {
		this.currentText = text;
	}

	public BackParam getBackgroud() {
		return backgroud;
	}

	public void setBackgroud(BackParam backgroud) {
		this.backgroud = backgroud;
	}

	public AlignMode getAlign() {
		return align;
	}

	public void setAlign(AlignMode align) {
		this.align = align;
	}

	public ShowType getScroll_type() {
		return scroll_type;
	}

	public void setScroll_type(ShowType scroll_type) {
		this.scroll_type = scroll_type;
	}

	public FontParam getFont() {
		return font;
	}

	public void setFont(FontParam font) {
		this.font = font;
	}

	public long getRefresh_time() {
		return refresh_time;
	}

	public void setRefresh_time(int refresh_time) {
		this.refresh_time = refresh_time;
	}

	public ArrayList<String> getText_list() {
		return text_list;
	}

	public void setText_list(ArrayList<String> text_list) {
		this.text_list = text_list;
	}
	
	public int getModule_type() {
		return module_type;
	}

	public void setModule_type(int module_type) {
		this.module_type = module_type;
	}

	public int getzOrder() {
		return zOrder;
	}

	public void setzOrder(int zOrder) {
		this.zOrder = zOrder;
	}

	public String getFile_version() {
		return file_version;
	}

	public void setFile_version(String file_version) {
		this.file_version = file_version;
	}

	public String getModule_name() {
		return module_name;
	}

	public void setModule_name(String module_name) {
		this.module_name = module_name;
	}

	public int getModule_uid() {
		return module_uid;
	}

	public void setModule_uid(int module_uid) {
		this.module_uid = module_uid;
	}

	public int getModule_gid() {
		return module_gid;
	}

	public void setModule_gid(int module_gid) {
		this.module_gid = module_gid;
	}

	/**
	 * @return the isReceive
	 */
	public boolean isReceive() {
		return isReceive;
	}

	/**
	 * @param isReceive the isReceive to set
	 */
	public void setReceive(boolean isReceive) {
		this.isReceive = isReceive;
	}

	/**
	 * @return the temp_list
	 */
	public ArrayList<String> getTemp_list() {
		return temp_list;
	}

	/**
	 * @param temp_list the temp_list to set
	 */
	public void setTemp_list(ArrayList<String> temp_list) {
		this.temp_list = temp_list;
	}
	
	
}
